/*
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * DMGIS. You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with DMGIS.
 *
 */
package com.dmgis.qxfw.utils;

import org.apache.commons.lang3.StringEscapeUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public final class PGUtil {

    public static ArrayList<Map<String, Object>> getResultSet2MapArr(String connectUrl, String userName,
                                                                     String passWord, String strSql) {
        ArrayList<Map<String, Object>> resultMap = new ArrayList<>();
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {
                Statement st = conn.createStatement();
                ResultSet rs = st.executeQuery(strSql);
                ResultSetMetaData metaData = rs.getMetaData();
                int colCount = rs.getMetaData().getColumnCount();
                while (rs.next()) {
                    HashMap<String, Object> tempMap = new HashMap<String, Object>();
                    for (int i = 1; i <= colCount; i++) {
                        tempMap.put(metaData.getColumnName(i),
                                rs.getObject(i, Class.forName(metaData.getColumnClassName(i))));
                    }
                    resultMap.add(tempMap);
                }
                rs.close();
                st.close();
                conn.close();
            } catch (Exception e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 数据服务更新接口
     *
     * @param connectUrl
     * @param userName
     * @param passWord
     * @param strSql
     * @return
     */
    public static String getResultSetJsonString(String connectUrl, String userName, String passWord, String strSql) {
        StringBuffer jsonStr = new StringBuffer();
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {
                Statement st = conn.createStatement();
                ResultSet rs = st.executeQuery(strSql);
                ResultSetMetaData metaData = rs.getMetaData();
                int colCount = rs.getMetaData().getColumnCount();
                jsonStr.append("[");
                String regEx = "[`~!\"@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                Pattern pattern = Pattern.compile(regEx);
                while (rs.next()) {
                    jsonStr.append("{");
                    for (int i = 1; i <= colCount; i++) {
                        jsonStr.append("\"" + metaData.getColumnName(i) + "\":");
                        String dataType = metaData.getColumnClassName(i);
                        Object value = rs.getObject(i);
                        if (dataType.contains("Int") || dataType.contains("Double") || dataType.contains("Float")) {
                            jsonStr.append(value + ",");
                        } else {
                            if (value == null)
                                value = "";
                            if (pattern.matcher(value.toString()).find()) {
                                value = StringEscapeUtils.escapeJson(value.toString());
                            }
                            jsonStr.append("\"" + value + "\",");
                        }
                    }
                    jsonStr.replace(jsonStr.length() - 1, jsonStr.length(), "},");
                }
                if (jsonStr.length() > 1) {
                    jsonStr.replace(jsonStr.length() - 1, jsonStr.length(), "]");
                } else {
                    jsonStr.append("]");
                }
                rs.close();
                st.close();
                conn.close();
            } catch (Exception e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                jsonStr.delete(0, jsonStr.length());
                jsonStr.append(e.getMessage());
                //e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonStr.toString();
    }

    public static Object[] getResultSetStringArr(String connectUrl, String userName, String passWord, String strSql) {
        // String jsonStr = "";
        ArrayList<String> arrayList = new ArrayList<String>();
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {

                Statement st = conn.createStatement();
                ResultSet rs = st.executeQuery(strSql);
                ResultSetMetaData metaData = rs.getMetaData();
                int colCount = rs.getMetaData().getColumnCount();
                while (rs.next()) {
                    // jsonStr = "[{";
                    String temp = "";
                    for (int i = 1; i <= colCount; i++) {
                        temp += rs.getObject(i, Class.forName(metaData.getColumnClassName(i))) + "|";
                    }
                    arrayList.add(StringUtil.trimEnd(temp, '|'));
                }
                rs.close();
                st.close();
                conn.close();
            } catch (Exception e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                arrayList = new ArrayList<String>();
                arrayList.add("无");
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return arrayList.toArray();
    }

    /**
     * 获取实体类集合
     *
     * @param resultSet
     * @param className
     * @return
     * @author dsq
     * @date 2018年10月31日
     */
    public static <T> List<T> getBeans(ResultSet resultSet, Class<T> className) {
        List<T> list = new ArrayList<T>();
        Field fields[] = className.getDeclaredFields();
        try {
            while (resultSet.next()) {
                T instance = className.newInstance();
                for (Field field : fields) {
                    String columnName = field.getName();
                    Type columnType = field.getType();
                    if (!existColumn(resultSet, columnName)) {
                        continue;
                    }
                    Object result = resultSet.getObject(columnName);
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    if (columnType == String.class) {
                        field.set(instance, result == null ? null : result.toString());
                    } else {
                        field.set(instance, result);
                    }
                    field.setAccessible(flag);
                }
                list.add(instance);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取实体类集合
     *
     * @param connectUrl
     * @param userName
     * @param passWord
     * @param strSql
     * @param className
     * @return
     * @author dsq
     * @date 2018年10月31日
     */
    public static <T> List<T> getBeans(String connectUrl, String userName, String passWord, String strSql,
                                       Class<T> className) {
        List<T> list = new ArrayList<T>();
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {

                Statement st = conn.createStatement();
                ResultSet resultSet = st.executeQuery(strSql);
                list = getBeans(resultSet, className);
                resultSet.close();
                st.close();
                conn.close();
            } catch (Exception e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return list;
    }

    /**
     * 获取实体类
     *
     * @param resultSet
     * @param className
     * @return
     * @author dsq
     * @date 2018年10月31日
     */
    public static <T> T getBean(ResultSet resultSet, Class<T> className) {
        T instance = null;
        try {
            instance = className.newInstance();
            Field fields[] = className.getDeclaredFields();
            for (Field field : fields) {
                String columnName = field.getName();
                Type columnType = field.getType();
                if (!existColumn(resultSet, columnName)) {
                    continue;
                }
                Object result = resultSet.getObject(columnName);
                boolean flag = field.isAccessible();
                field.setAccessible(true);
                if (columnType == String.class) {
                    field.set(instance, result == null ? null : result.toString());
                } else {
                    field.set(instance, result);
                }
                field.setAccessible(flag);
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return instance;
    }

    /**
     * 获取实体类
     *
     * @param connectUrl
     * @param userName
     * @param passWord
     * @param strSql
     * @param className
     * @return
     * @author dsq
     * @date 2018年10月31日
     */
    public static <T> T getBean(String connectUrl, String userName, String passWord, String strSql, Class<T> className) {
        T instance = null;
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {

                Statement st = conn.createStatement();
                ResultSet resultSet = st.executeQuery(strSql);
                resultSet.next();
                if (resultSet.getRow() < 1) {
                    return null;
                }
                instance = getBean(resultSet, className);
                resultSet.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return instance;
    }

    /**
     * 插入图片,单条记录有返回值，多条没有
     *
     * @param connectUrl
     * @param userName
     * @param passWord
     * @param strSql
     * @return
     * @author dsq
     * @date 2018年11月1日
     */
    public static int ExecuteNoQuery(String connectUrl, String userName, String passWord, String strSql) {
        int count = 0;
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {
                PreparedStatement st = conn.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS);
                st.executeUpdate();
                ResultSet generatedKeys = st.getGeneratedKeys();
                if (generatedKeys.next()) {
                    count = generatedKeys.getInt(1);
                }
                st.close();
                conn.close();
            } catch (Exception e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    /**
     * 更新插入数据，没有returning
     *
     * @param connectUrl
     * @param userName
     * @param passWord
     * @param strSql
     * @return
     * @author dsq
     * @date 2018年11月6日
     */
    public static int ExecuteNoQueryWithoutReturning(String connectUrl, String userName, String passWord,
                                                     String strSql) {
        int count = 0;
        try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection(connectUrl, userName, passWord);
            try {

                PreparedStatement st = conn.prepareStatement(strSql);
                st.execute();
                while (true) {
                    int rowCount = st.getUpdateCount();
                    if (rowCount > 0) { // 它是更新计数
                        st.getMoreResults();
                        count++;
                        continue;
                    }
                    if (rowCount == 0) { // DDL 命令或 0 个更新
                        st.getMoreResults();
                        count++;
                        continue;
                    }
                    break;
                }
                st.close();
                conn.close();
            } catch (Exception e) {
                if (!conn.isClosed()) {
                    conn.close();
                }
                count = -1;
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return count;
    }

    /**
     * 检查数据库表是否存在
     *
     * @param connectUrl
     * @param userName
     * @param passWord
     * @param tableName
     * @return
     * @throws Exception
     */
    public static boolean ExistTable(String connectUrl, String userName, String passWord, String tableName) throws Exception {
        if ("pg_tables".equals(tableName))
            return true;
        String strSql = "SELECT u.tablename  FROM pg_catalog.pg_tables u where u.tablename='" + tableName + "';";
        Connection conn = null;
        Class.forName("org.postgresql.Driver");
        conn = DriverManager.getConnection(connectUrl, userName, passWord);
        Statement st = conn.createStatement();
        ResultSet resultSet = st.executeQuery(strSql);
        resultSet.next();
        if (resultSet.getRow() < 1) {
            st.close();
            conn.close();
            return false;
        } else {
            st.close();
            conn.close();
            return true;
        }
    }

    /**
     * 判断字段是否存在
     *
     * @param resultSet
     * @param column
     * @return
     */
    private static boolean existColumn(ResultSet resultSet, String column) {
        Boolean existBoolean = false;
        try {
            if (resultSet.findColumn(column) > 0) {
                existBoolean = true;
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return existBoolean;
    }
}
